#pragma once

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include<string>
#include"nocopy.hpp"
#include"Log.hpp"
#include"InetAddr.hpp"
using namespace log_ns;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;

enum{
    SOCKET_ERROR = -1,
    BIND_ERROR = -2
};

//udpsever user("192.1.1.1, 8888")
class UdpSever : public nocopy //防止服务器拷贝
{
public:
    UdpSever(uint16_t localport = glocalport)
        :_sockfd(gsockfd), 
         _localport(localport)
    {

    }

    void InitSever()
    {
        //1. 创建socket套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0); //创建套接字 网络通信， 数据报， 协议格式
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error \n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd: %d\n", _sockfd); //3

        //客户端和服务器都学要ip + port

        //2.bind 
            //填充本地信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);//两字节port 传输时需要考虑大小端 主机序列转网络序列
        //local.sin_addr.s_addr = inet_addr(_localip.c_str()); //用户输入的ip是字符串 1.需要4字节ip 2. 需要网络序列ip
        local.sin_addr.s_addr = INADDR_ANY; //网络地址任意 进行任意ip地址绑定

        int n = bind(_sockfd, (const sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error \n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind success, _sockfd: %d\n", _sockfd);
    }

    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while(_isrunning)
        {
            struct sockaddr_in peer; // 远端信息
            socklen_t len = sizeof(peer);
            //后两位输入输出型参数  fd 缓冲区 缓冲区大小 格式 sockaddr sockaddr大小
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                InetAddr addr(peer);
                // uint16_t peerport = ntohs(peer.sin_port); //从网络序列到主机序列
                // std::string peerip = inet_ntoa(peer.sin_addr);

                //n 是缓冲区大小
                inbuffer[n] = 0;
                std::cout << "[" << addr.Ip() << ':' << addr.Port() << "]" << inbuffer << std::endl;

                std::string echo_string = "[udp_sever echo] #";
                echo_string += inbuffer;  

                //发
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr*)&peer, len);            
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
            }
        }
        _isrunning = false;

    }

    ~UdpSever()
    {
        if(_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip; //暂时这么写
    bool _isrunning;
};